var mouseFlag = false;
var play1 = false;
var play2 = false;
var play3 = false;
var play4 = false;


String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};
function dateFtt(fmt,date) {
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
$(function () {

    // 获取信息并执行滚动
    getMessageLeast();
    setInterval(function () {
        if (!mouseFlag) getMessageLeast();
    }, 1000 * 30);

    // 鼠标经过暂停信息滚动
    $(document).on("mouseover", ".message-area", function () {
        mouseFlag = true;
        clearInterval(msgTimer);
    }).on("mouseout", ".message-area", function () {
        mouseFlag = false;
        msgScroll();
    });

    // 点击带有“show-carinfo”，弹出车辆详情窗体
    $(document).on("click", ".show-carinfo", function () {
        var carId = $(this).data("carid");
        if (typeof carId !== 'undefined') {
            getCarDetailByType(carId, 1);
        } else {
            var carNumber = $(this).data("id");
            getCarDetailByType(carNumber, 2);
        }
    });

    // 点击带有“show-pointinfo”，弹出乘车点详情窗体
    $(document).on("click", ".show-pointinfo", function () {
        var pointId = $(this).data("pointid");
        getRidePointDetailById(pointId);
    });

});

// 获取信息
var getMessageLeast = function () {
    console.log("获取实时消息...");
    $.ajax({
        url: 'getMessageLeast.do',
        type: "GET",
        success: function (result) {
            clearInterval(msgTimer);
            var newHtml = '';
            $('.message-area>ul').empty();
            var messagesList = result.data;
            for (var m in messagesList) {
                var msg = messagesList[m];
                var msgNote = changeNote(msg);
                var d = new Date(msg.feedbackDate);
                var time = dateFtt("hh:mm:ss",d);
                newHtml += '<li>【' + time + '】' + msgNote + '</li>';
            }
            $('.message-area>ul').append(newHtml);
            msgScroll();
        }
    })
};


/**
 * 处理滚动信息
 * @param msg   信息数据本体
 * @returns {*}   输出处理后的信息html
 */
function changeNote(msg) {
    // 替换车辆文本 msg.airRidePoint.name+"&nbsp;&nbsp;"+msg.title+"&nbsp;&nbsp;"+
    var ridePointId = msg.airRidePoint.id;
    var note = msg.note;
    var car_number_catch = /粤[A-Za-z0-9]{6}|粵[A-Za-z0-9]{5}港/g;
    var car_number_match = note.match(car_number_catch);
    for (var c in car_number_match) {
        if (car_number_match !== null) {
            var car = '<em class="show-carinfo" data-id="' + car_number_match[c] + '">' + car_number_match[c] + '</em> ';
            note = note.replace(car_number_match[c], car);
        }
    }
    note = '<em class="show-pointinfo" data-pointid="' + ridePointId + '">' + msg.airRidePoint.name + '</em> ' + "&nbsp;&nbsp;" + msg.title + "&nbsp;&nbsp;" + note;
    return note
}

// 信息滚动
var msgTimer;

function msgScroll() {
    var $ul = $('.message-area .roll__list'),
        $item = $ul.find('li'),
        offset, i,
        $sliceItem = $($item[0]),
        range = $sliceItem.outerWidth(true);
    // 开始循环滚动
    msgTimer = setInterval(function () {
        offset = $ul.css('left');
        offset = parseInt(offset);
        if (offset > -range) {
            i = offset - 1;
            $ul.css('left', i + 'px');
            offset = $ul.css('left');
        } else {
            $sliceItem.detach();
            $ul.css('left', 0);
            $ul.append($sliceItem);
            $sliceItem = $($ul.find('li')[0]);
            range = $sliceItem.outerWidth(true);
        }
    }, 40);
}


// 打开车辆详情弹窗
function getCarDetailByType(param, type) {
    $("#ridePointDetailDiv").css("visibility", "hidden");
    var params = {};
    var url = "";
    if (type === 1) {
        params["id"] = param;
        url = "getCarDetailByCarId.do";
    } else {
        params["carNumber"] = param;
        url = "getCarDetailByCarNumber.do";
    }
    $.ajax({
        url: url,
        type: "GET",
        data: params,
        success: function (result) {
            if (typeof result.data !== 'undefined') {
                var car = result.data;
                var driver = result.data.driver;
                var point = result.data.airRidePoint;
                $("#car_type").html(car.type);
                $(".car_number").html(car.carNumber);
                // $("#car_belong").html(car.belongUnit);
                $("#car_seating").html(car.seating);
                $("#car_status").html(getStatusNote(car.status));
                $("#car_date").html(car.modificationDate);
                if (typeof driver !== 'undefined') {
                    $("#car_name").html(driver.name);
                    $("#car_interphone").html(driver.interphone);
                    $("#car_phone").html(driver.phone);
                }
                if (typeof point !== 'undefined') {
                    $(".car_startpointName").html(point.name);
                    // $("#car_consuming").html(point.consumed);
                    var route = (point.route>0?point.route:"")+" ";
                    $("#car_pointName").html(route+point.name).data("pointid", point.id);
                    $("#car_leader").html(point.leader);
                    if(point.consumed){
                        $("#consumed").html(point.consumed+"分钟");
                    }
                    $("#leader_phone").html(point.phone);
                    // $("#point_position").html(point.position);
                    var parking = point.airParkingLot;
                    if (typeof parking !== 'undefined') {
                        $(".car_tarplace").html(parking.name);
                    }
                }
                catchCarOffset(car);
                initCarMap(car);
                $(".window-layer").css("z-index", 500);
                $("#carDetailDiv").css("z-index", 1000).show();
            } else {
                alert("查无此车，请核对数据！");
            }
        }
    })
}

// 初始化地图,并获取车辆定位信息
var initCarMap = function (car) {
    if (typeof car.lon !== 'undefined' && typeof car.lat !== 'undefined') {
        var map = new AMap.Map('mapBox', {
            zoom: 11, //初始化地图层级
            center: [car.lon, car.lat] //初始化地图中心点
        });
        var maker = new AMap.Marker({
            position: new AMap.LngLat(car.lon, car.lat),
            title: car.carNumber
        });
        map.add(maker);
        AMap.plugin('AMap.Geocoder', function () {
            var geocoder = new AMap.Geocoder({
                city: '珠海',
            });
            var lnglat = [car.lon, car.lat];
            geocoder.getAddress(lnglat, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    // result为对应的地理位置详细信息
                    var address = result.regeocode.addressComponent;
                    $("#car_position").html(address.city + address.district + address.township + address.street + address.streetNumber);
                }
            })
        });
    } else {
        var map = new AMap.Map('mapBox', {
            zoom: 11, //初始化地图层级
            center: [113.58397428, 22.2790923] //初始化地图中心点
        });
        $("#car_position").html("未知位置");
    }
};

// 车辆状态
var statusNote = ['待发车', '已发车', '已到达', '已返程'];
var getStatusNote = function (status) {
    if (typeof status === 'undefined'||status == null || status == '') {
        return 'GPS异常';
    }
    return statusNote[status - 1];
}

// 判断车辆GPS状态
var catchCarOffset = function (car) {
    var status = car.status;
    if (typeof status === 'undefined'||status == null || status == '') {
        $("#mapBox").parent().addClass("map-box-error");
        $(".error-tip span").html("GPS异常！！");
    }else if(typeof car.lon !== 'undefined') {
        $("#mapBox").parent().removeClass("map-box-error");
        if (car.isOnline === -1) {
            $("#mapBox").parent().addClass("map-box-deviate");
            $(".error-tip span").html("车辆偏离路线！！");
        }
        else {
            $("#mapBox").parent().removeClass("map-box-deviate");
            $(".error-tip span").html("");
        }
    }
};

// 关闭车辆详情弹窗
function CloseCarDetailDiv() {
    $("#carDetailDiv").hide();
    if (!$("#ridePointDetailDiv").is(":hidden")) {
        $("#ridePointDetailDiv").css("visibility", "visible");
    }
}


// 打开乘车点详情弹窗
function getRidePointDetailById(id) {
    $("#ridePointDetailDiv").css("visibility", "visible");
    console.log("获取乘车点id" + id);
    $.ajax({
        url: "getRidePointDetailById.do",
        type: "GET",
        data: {id: id},
        success: function (result) {
            var arp = result.data.airRidePoint;
            var carList = result.data.carList;
            var workerList = result.data.workerList;
            fillInfo(carList, workerList);
            var route = (arp.route>0?arp.route:"")+" ";
            $("#air_rp_name").html(route+arp.name + "");
            $("#air_rp_position").html(arp.position + "");
            $("#air_rp_leader").html(arp.leader + "");
            $("#air_rp_phone").html(arp.phone + "");
            if(arp.interphone) {
                $("#air_rp_interphone").html(arp.interphone + "");
            }
            if(arp.consumed) {
                $("#consume").html(arp.consumed + "分钟");
            }else {
                $("#consume").html("暂无数据");
            }
            $(".car_startpointName").html(arp.name + "");
            if (typeof arp.airParkingLot !== "undefined") {
                $(".car_tarplace").html(arp.airParkingLot.name + "");
            }
            // 启动视频
            if(arp.camera1 && arp.camera1.length > 0 ){
                play("pointCamera1",arp.camera1);
                play1 = true;
            }
            if(arp.camera2 && arp.camera2.length > 0 ){
                play("pointCamera2",arp.camera2);
                play2 = true;
            }
            if(arp.camera3 && arp.camera3.length > 0 ){
                play("pointCamera3",arp.camera3);
                play3 = true;
            }
            if(arp.camera4 && arp.camera4.length > 0 ){
                play("pointCamera4",arp.camera4);
                play4 = true;
            }
            //play("pointCamera4","rtsp://admin:Thinkjoy2015@192.168.0.242:554/h264/ch1/main/av_stream");
        }
    });
    $(".window-layer").css("z-index", 500);
    $("#ridePointDetailDiv").css("z-index", 1000).show();
}


function fillInfo(carList, workerList) {
    var seatSum = 0;
    $("#drivers").empty();
    for (var c in carList) {
        var car = carList[c];
        if(car.seating) seatSum += car.seating;
        var driver = car.driver;
        var driver_name = '未知', driver_phone = '未知', driver_interphone = '未知';
        if (typeof driver !== 'undefined') {
            driver_name = (typeof driver.name === 'undefined' ? '暂无司机名字' : driver.name);
            driver_phone = (typeof driver.phone === 'undefined' ? '暂无司机电话' : driver.phone);
            driver_interphone = (typeof driver.interphone === 'undefined' ? '暂无对讲机' : driver.interphone);
        }
        var html = '<li class=\"show-carinfo\" data-carid="' + car.id + '">\n' +
            "                        <div>\n" +
            "                            <span>" + car.carNumber + "</span>\n" +
            "                            <em>" + (car.seating ? car.seating+"座" : "") + "</em>\n" +
            "                            <em>" + getStatusNote(car.status) + "</em>\n" +
            "                        </div>\n" +
            "                        <p>\n" +
            "                            " + driver_name + " · " + driver_phone + " · " + driver_interphone + "\n" +
            "                        </p>\n" +
            "                    </li>";

        $("#drivers").append(html);
    }
    $("#air_rp_busSum").html(carList.length + "");
    $("#air_rp_seat").html(seatSum + "");

    var worker_p = "";
    for (var w in workerList) {
        var worker = workerList[w];
        if(worker.note == undefined || !worker.note.length>0) {
            worker_p += worker.name + " " + worker.phone + " 、 ";
        }
    }
    if (worker_p !== "") {
        worker_p = worker_p.substring(0, worker_p.length - 2);
    }
    $("#worker_p").html(worker_p);
}

// 关闭乘车点详情弹窗
function CloseRidePointDetailDiv() {
    $("#ridePointDetailDiv").hide();
    //结束所有监控视频
    if(play1){
        play1 = false;
        stop("pointCamera1");
    }
    if(play2){
        play2 = false;
        stop("pointCamera2");
    }
    if(play3){
        play3 = false;
        stop("pointCamera3");
    }
    if(play4){
        play4 = false;
        stop("pointCamera4");
    }
}

// 打开工作人员详情弹窗
function getWorkerDetailByData(data) {

    $("#worker_name").html(data.name);
    $("#worker_id").html(data.idNumber);
    $("#worker_belong").html(data.belongUnit);
    $("#worker_phone").html(data.phone);
    $("#worker_time").html(data.modificationDate);
    var route = (data.airRidePoint.route>0?data.airRidePoint.route:"")+" ";
    $("#worker_point_name").html(route + data.airRidePoint.name);
    $("#worker_point_name").data("pointid",data.airRidePoint.id);
    $("#worker_point_leader").html(data.airRidePoint.leader);
    $("#worker_point_leaderPhone").html(data.airRidePoint.phone);
    $("#worker_point_position").html(data.airRidePoint.position);
    $("#worker_point_car").html(data.airRidePoint.busSum);

    $(".window-layer").css("z-index", 500);
    $("#workerDetailDiv").css("z-index", 1000).show();
}

// 关闭乘车点详情弹窗
function CloseWorkerDetailDiv() {
    $("#workerDetailDiv").hide();
}


//播放视频
function play(id, href) {
    var vlc = document.getElementById(id);
    vlc.playlist.clear();
    vlc.playlist.add(href);
    vlc.playlist.play();
}

//停止播放
function stop(id) {
    var vlc = document.getElementById(id);
    vlc.playlist.stop();
}